package licode.unisop.client.utils;

import licode.unisop.client.api.auth.SopUserAuthQuery;
import licode.unisop.client.info.SopTokenInfo;
import licode.unisop.client.service.impl.SopAuthCheck;
import licode.unisop.client.vo.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author licode
 */
@Component
public class SopUserAuthQueryUtil {
    @Resource
    HttpServletRequest request;

    @Resource
    private SopAuthCheck sopAuthCheck;

    @Resource
    private SopUserAuthQuery queryAuth;

    @Resource
    private SopUserAuthQuery sopUserAuthQuery;

    private SopAuthPlatform checkPlatform(String plId) {
        SopAuthPlatform platform = sopAuthCheck.getPlatform(request);
        if (null == platform || !platform.isValid()) {
            // 平台不可用（在认证中心没有注册）
            throw new SopException(403, "无效平台！");
        }
        return platform;
    }

    private void checkToken(String accessToken) {
        if (StringUtil.isBlank(accessToken)) {
            throw new SopException(403, "无效登录信息！");
        }
    }

    private SopTokenInfo getAuthToken(String plId) {
        SopAuthPlatform platform = checkPlatform(plId);
        SopTokenInfo authToken = SopRequestParse.getAccessTokenInfo(request);
        authToken.setPlatformId(platform.getPlatformId());
        checkToken(authToken.getToken());
        return authToken;
    }

    public SopAuthBrief getTokenInfo() {
        SopTokenInfo tokenInfo = getAuthToken("");
        return sopUserAuthQuery.getAuthBrief(tokenInfo);
    }

    public SopAuthUser authUserInfo(String platformId) {
        return sopUserAuthQuery.getAuthUserInfo(getAuthToken(platformId));
    }

    public SopUserBrief getUserInfo(String platformId) {
        return sopUserAuthQuery.getUserInfo(getAuthToken(platformId));
    }

    public SopCredential getCredential(String platformId) {
        return sopUserAuthQuery.getCredential(getAuthToken(platformId));
    }

    public Map<String, Object> getUserAssets(String platformId) {
        SopTokenInfo tokenInfo = getAuthToken(platformId);
        return queryAuth.getUserAssets(tokenInfo);
    }

    public boolean tokenValid(SopTokenInfo tokenInfo) {
        return sopUserAuthQuery.tokenValid(tokenInfo);
    }
}
